
using System;
using System.Collections;
using System.IO;
using RSSRadio.Model;
using RSSRadio.Utility;

namespace RSSRadio
{
	public static class Globals
	{
		public static PodcastList DownloadedPodcasts;
		public static AppSettings AppSettings;
		public static ArrayList ActivePodcastDownloaders = new ArrayList();
        public static CustomThreadPool ThreadPool = new CustomThreadPool(2);

        private static SubscriptionManager feeds;

        private static String logFilename;
        //private static StreamWriter logFile;
        private static int maxLogSize = 65535;

		static Globals()
		{
			Load();
            feeds = new SubscriptionManager();
            //logFile= null;
            logFilename = getLogFilename();
            if (File.Exists(logFilename))
            {
                FileInfo fi = new FileInfo(logFilename);
                if (fi.Length > maxLogSize)
                {
                    try
                    {
                        fi.Delete();
                    }catch(Exception) {}
                }
            }
		}

		public static void Load()
		{
			AppSettings = new AppSettings();
			AppSettings.Read();
			DownloadedPodcasts = PodcastList.LoadFromXml(AppSettings.DownloadedPodcastListXmlLoc);
		}

        public static void logError(Exception e)
        {
            logError(String.Format("Logging Exception {0}\n", e.ToString()));
            logError(e.StackTrace);
        }
        public static void logError(String msg)
        {
            logError(new String [] {msg});
        }

        public static void logError(String[] msgs)
        {
            lock (logFilename)
            {
                using (StreamWriter log = File.AppendText(logFilename))
                {
                    foreach (String s in msgs)
                    {
                        log.Write("{0}\n", s);
                    }
                    log.Close();
                }
            }
        }

        private static String getLogFilename()
        {
		    try
		    {
                logFilename = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\RSSRadio\\RSSRadio.txt";
		    }
		    catch
		    {
			    // workaround lack of application data folder on WM 2003
                logFilename = "\\Program Files\\RSSRadio\\RSSRadio.txt";
		    }
            return logFilename;

        }

        public static SubscriptionManager getSubscriptionManager()
        {
            return feeds;
        }
	}
}
